package com.yonyou.sto.modules.ims.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.yonyou.sto.domain.InvoiceStatusEnums;
import com.yonyou.sto.modules.ims.dto.InvoiceDto;
import com.yonyou.sto.modules.ims.dto.PushBillParam;
import com.yonyou.sto.modules.ims.model.ImsBill;
import com.yonyou.sto.modules.ims.model.ImsInvoice;
import com.yonyou.sto.modules.ims.model.ImsInvoiceItem;
import com.yonyou.sto.modules.ims.service.ImsInvoiceItemService;
import com.yonyou.sto.modules.ims.service.ImsInvoiceService;
import com.yonyou.sto.modules.ims.service.ImsReturnInvoiceService;
import com.yonyou.sto.modules.ims.service.PushBillService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Aegon Targaryen
 * @date Created in 2020/10/10 11:30
 * @description: TODO
 */
@Service
public class PushBillServiceImpl implements PushBillService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PushBillServiceImpl.class);

    @Value("${yuewen.push}")
    private String PUSH;

    @Value("${yuewen.return}")
    private String RETURN;

    @Resource
    private ImsInvoiceService invoiceService;

    @Resource
    private ImsInvoiceItemService invoiceItemService;

    @Resource
    private ImsReturnInvoiceService returnInvoiceService;

    @Override
    public Map<String, String> pushBillClient(List<InvoiceDto> dtos) {

        String testUrl = "http://116.231.81.116:54333/contr-zc/contr/commonBillInfoCreate.do";
        String proUrl = "http://220.248.45.43:18098/ZC/contr/commonBillInfoCreate.do";

        List<PushBillParam> params = new ArrayList<>();
        dtos.forEach(dto -> {
            PushBillParam param = new PushBillParam();
            param.setNoticeId(Long.parseLong(dto.getBillSn()));
            param.setNcId(dto.getBillSerial());
            param.setNoTaxAmount(dto.getPayAmount().doubleValue());
            param.setTaxAmount(dto.getTaxAmount().doubleValue());
            param.setBillNo(dto.getBillSerial());
            //param.setBillDate(dto.getCreateTime());
            param.setBillType("Invoice");
            param.setStatus("Effective");
            params.add(param);
        });

        return push(PUSH, params);
    }

    @Override
    public Map<String, String> pushBillClient1(String status, List<ImsBill> dtos) {

        String testUrl = "http://116.231.81.116:54333/contr-zc/contr/commonBillInfoCreate.do";
        String proUrl = "http://220.248.45.43:18098/ZC/contr/commonBillInfoCreate.do";

        List<PushBillParam> params = new ArrayList<>();
        dtos.forEach(dto -> {
            PushBillParam param = new PushBillParam();
            param.setNoticeId(Long.parseLong(dto.getBillSn()));
            param.setNcId(dto.getBillSerial());
            param.setNoTaxAmount(dto.getPayAmount().doubleValue());
            param.setTaxAmount(dto.getTaxTotal().doubleValue());
            param.setBillNo(dto.getBillSerial());
            param.setBillType("Invoice");
            param.setStatus(status);
            params.add(param);
        });

        return push(PUSH, params);
    }

    @Override
    public Map<String, String> pushReturn(List<ImsInvoice> imsInvoices) {
        String testUrl = "http://116.231.81.116:54333/contr-zc/contr/commonInvalidInfoCreate.do";
        String proUrl = "http://220.248.45.43:18098/ZC/contr/commonInvalidInfoCreate.do";

        List<PushBillParam> params = new ArrayList<>();
        imsInvoices.forEach(i -> {
            PushBillParam param = new PushBillParam();
            param.setNoticeId(Long.parseLong(i.getBillSn()));
            param.setNcId(i.getId().toString());
            param.setInvalidDate(DateUtil.format(DateUtil.parse(i.getCreateTime()), DatePattern.PURE_DATE_PATTERN));
            params.add(param);
            i.setStatus(InvoiceStatusEnums.RETURN.getCode());
        });

        return push(RETURN, params);
    }

    public <E> Map<String, String> push(String url, List<E> param) {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        Map<String, String> map = new HashMap<>();

        try {
            GsonBuilder builder = new GsonBuilder();
            String encode = URLEncoder.encode(builder.create().toJson(param), "UTF-8");
            HttpGet get = new HttpGet(url + "?jsonData=" + encode);

            response = client.execute(get);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);

            LOGGER.debug(result);

            Gson gson = new Gson();
            return gson.fromJson(result, map.getClass());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
